import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.LinkedList;
import java.util.Observable;

import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPanel;

import command.Commande;
import command.Invoqueur;

/*
 * Avant tout commit (Clique droit sur le projet >> Team >> Commit) je te propose d'ecrire ci dessous les modif ajoutées
 * 13-11-2012 : Mise en place du SVN
 * 15-11-2012 : Zoom et déplacement opérationnel début du changement en patron Command
 * 16-11-2012 : Panneau image utilise Singleton/Debut de Command
 * 17-11-2012 : Implémentation du patron Command
 * 21-11-2012 : Utilisation de la fontion Annuler (Historique de commande)
 * 27-11-2012 : On a fait pein de trucs
 */

@SuppressWarnings("serial")
public class FenetreMain extends WindowFactory implements ActionListener, MouseWheelListener, MouseListener, MouseMotionListener, WindowListener{

	@SuppressWarnings("unused")
	private MenuPerso menu;
	private RecepteurPanneauImage image; 
	private Mediator med = Mediator.getInstance();
	private int x;
	private int y;

	private Invoqueur lInvoqueur = Invoqueur.getInstance();
    private Strategie lStrategieA = new StrategyEnregistrementImage();
    private Strategie lStrategieB = new StrategyEnregistrementFermeture();
    private static WindowFactory window = WindowFactory.createWindow("Main");
    private WindowFactory windowZoomPosition = WindowFactory.createWindow("ZoomPos");
    private WindowFactory vignette = WindowFactory.createWindow("Vignette");
    private WindowFactory windowSauvegarde;
    
    public FenetreMain() {
        
    }
   
    public void createMainWindow()
    {
           
            this.setTitle("Editeur d'image");
        menu=new MenuPerso(this);
        JPanel background = new JPanel();
        background.setBackground(Color.white);
        this.setContentPane(background);
        this.setExtendedState(this.getExtendedState() | FenetreMain.MAXIMIZED_BOTH);
        this.setLocationRelativeTo(null);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);            
        this.setVisible(true);
           
    }

	
	public static WindowFactory getInstance(){
		if(window == null)
			window= new FenetreMain();		
		return window;
	}
	
	public static void main(String[] args) {
		window.createMainWindow();
		
	}

	@Override
	public void actionPerformed(ActionEvent arg0) {
		JMenuItem source = (JMenuItem) (arg0.getSource());
		String sourceText = source.getText();
		System.out.println(sourceText);
		if (sourceText.equals("Ouvrir")	&& this.isActive()) {
		/*
			 * Ouverture du BROWSER pour récupérer l'image
			 */
			JFileChooser browser = new JFileChooser();
			browser.setVisible(true);
			JPanel windowBroozer = new JPanel();
			File img=null;
			if(browser.showDialog(windowBroozer,"Ouvrir")==JFileChooser.APPROVE_OPTION){
				img = browser.getSelectedFile();
			}
			image=RecepteurPanneauImage.getInstance();
			image.setSize(this.getSize());
			image.setPreferredSize(this.getPreferredSize());
			
			//windowZoomPosition.setZoomPos(image.getZoomPosition());
			
				
			ZoomPosition.getInstance().getObs().addObserver(windowZoomPosition);
			ZoomPosition.getInstance().getObs().addObserver(image);
			image.addPic(img);
			
			
			med.registerFenetreVignette(vignette);
			med.registerFenetreZoomPos(windowZoomPosition);
			med.setMenuEnabled();
			
			
			vignette.addPic(img);
			this.add(image);
			this.addMouseWheelListener(this);
			this.addMouseMotionListener(this);
			this.addMouseListener(this);
			this.repaint();

		} else if(sourceText.equals("Fermer fichier")&& this.isActive()) {
			/*
			 * On ferme le fichier
			 */
			this.remove(image);
			this.repaint();
			//menu.menuBeforeOuvrir(false);
			med.setMenuDisabled();
			lInvoqueur.setHistory(new LinkedList<Commande>());
		} else if(sourceText.equals("Sauvegarder") && this.isActive()) {
			windowSauvegarde = WindowFactory.createWindow("Sauvegarde");
			windowSauvegarde.addWindowListener(this);
			
			 
		} else if (sourceText.equals("Charger") && this.isActive()){
			
			File doffier = new File(System.getProperty("user.dir" ));
			doffier.mkdir();
			JFileChooser browser = new JFileChooser(doffier);
			browser.setVisible(true);
			JPanel windowBroozer = new JPanel();
			if(browser.showDialog(windowBroozer,"Ouvrir")==JFileChooser.APPROVE_OPTION){
				File nomFichier = browser.getSelectedFile();
				try {
					FileInputStream fis = new FileInputStream(nomFichier.getPath());
					image=RecepteurPanneauImage.getInstance();
					image.restaurerDepuisMemento(fis);
				} catch (IOException e) {
					e.printStackTrace();
				}		
			
			}
			repaint();
		
		} else if (sourceText.equals("Quitter") && this.isActive()){
			System.exit(0);
		} else if (sourceText.equals("Annuler") && this.isActive()){
			LinkedList<Commande> history= lInvoqueur.getHistory();
			if (history.isEmpty()){
				System.out.println("Vide");
			} else {
				history.removeFirst();
				Commande lastAdd=history.pop();
				if (lastAdd.toString().contains("ConcreteCommandeModifPos")){
					System.out.println(lastAdd.toString());
					((ConcreteCommandeModifPos)lastAdd).setI(((ConcreteCommandeModifPos)lastAdd).getI());
					((ConcreteCommandeModifPos)lastAdd).setJ(((ConcreteCommandeModifPos)lastAdd).getJ());
					lInvoqueur.setCommandeModifPos(lastAdd);
					lInvoqueur.invoquerModifPos();
					repaint();
				} else if (lastAdd.toString().contains("ConcreteCommandeModifZoom")) {
					System.out.println(lastAdd.toString());
					((ConcreteCommandeModifZoom)lastAdd).setI(((ConcreteCommandeModifZoom)lastAdd).getI());
					lInvoqueur.setCommandeModifZoom(lastAdd);
					lInvoqueur.invoquerModifZoom();
					repaint();
				}
				if(!lInvoqueur.getHistory().isEmpty())
					lInvoqueur.getHistory().pop();
			}
		}

		
	}

	@Override
	public void mouseWheelMoved(MouseWheelEvent e) {
		lInvoqueur.setSwithCom(0);
        ConcreteCommandeModifZoom lCommandeA = new ConcreteCommandeModifZoom(this.image);
		if(e.getWheelRotation()==-1.0){
			lCommandeA.setI(ZoomPosition.getInstance().getZoom()+0.01);
		} else if (e.getWheelRotation()==1.0){
			if((ZoomPosition.getInstance().getZoom()-0.01)>=0){
				lCommandeA.setI(ZoomPosition.getInstance().getZoom()-0.01);
			}
		}
        lInvoqueur.setCommandeModifZoom(lCommandeA);
		lInvoqueur.invoquerModifZoom();
		lInvoqueur.setSwithCom(1);
		repaint();
	}

	@Override
	public void mouseDragged(MouseEvent e) {
		if((e.getButton()==0)){
			ConcreteCommandeModifPos lCommandeB = new ConcreteCommandeModifPos(this.image);
			lCommandeB.setI(ZoomPosition.getInstance().getX()+(e.getX()-x));
			lCommandeB.setJ(ZoomPosition.getInstance().getY()+(e.getY()-y));
			lInvoqueur.setCommandeModifPos(lCommandeB);
			lInvoqueur.invoquerModifPos();
			x=e.getX();
			y=e.getY();
			repaint();
		}
	}

	@Override
	public void mousePressed(MouseEvent e) {
		if(e.getButton()==1){
			x=e.getX();
			y=e.getY();
		}
	}

	@Override
	public void mouseReleased(MouseEvent e) {}
	
	@Override
	public void mouseMoved(MouseEvent e) {
	}

	@Override
	public void mouseClicked(MouseEvent e) {
	}

	@Override
	public void mouseEntered(MouseEvent e) {
	}

	@Override
	public void mouseExited(MouseEvent e) {
	}

	@Override
	public void windowActivated(WindowEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowClosed(WindowEvent arg0) {
		if (windowSauvegarde.getChoice() == 0) {
			 Sauvegarde lClasseB = new Sauvegarde(lStrategieB);
			 lClasseB.operation(windowSauvegarde.getName());
		} else if (windowSauvegarde.getChoice() == 1) {
			Sauvegarde lClasseA = new Sauvegarde(lStrategieA);
			lClasseA.operation(windowSauvegarde.getName());
		}
	}

	@Override
	public void windowClosing(WindowEvent arg0) {
	}

	@Override
	public void windowDeactivated(WindowEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowDeiconified(WindowEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowIconified(WindowEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowOpened(WindowEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void update(Observable o, Object arg) {
		// TODO Auto-generated method stub
		
	}


}

